<template>
    <view class="container">
        <view class="food-popup">
            <view class="food-search">
                <tn-input v-model="searchKeyword" placeholder="搜索食物" border></tn-input>
            </view>

            <scroll-view scroll-y class="food-list">
                <view v-for="(food, index) in filteredFoodList" :key="index" class="food-item" @tap="selectFood(food)">
                    <view class="food-name">{{ food.names }}</view>
                    <view class="food-calories">{{ food.reliangNum }}千卡 / {{ food.weight + food.units }}</view>
                </view>
            </scroll-view>

            <view class="selected-foods">
                <view class="selected-title">已选择食物</view>
                <scroll-view scroll-y class="selected-foods-list">
                    <view v-for="(item, index) in selectedFoods" :key="index" class="selected-food-item">
                        <view class="selected-food-name">{{ item.food.names }}</view>

                        <view class="selected-food-calories">{{ (item.food.reliangNum * item.amount).toFixed(0) }}千卡</view>
                        <text class="remove-btn tn-icon-close" @tap="removeFood(index)"></text>
                    </view>
                </scroll-view>

                <view class="total-calories">总热量: {{ getTotalCalories() }}千卡</view>
            </view>

            <view class="popup-actions">
                <view class="save-btn cancel" @tap="handleCancel">取消</view>
                <view class="save-btn" @tap="addRecord">保存</view>
            </view>
        </view>
    </view>
</template>

<script>
import foodList from './static/foodData.json';
import { formatDate } from '@/store/utils';
const record = uniCloud.importObject('record', {
    customUI: true
});

export default {
    data() {
        return {
            dateList: [],
            category: '',
            daysInMonth: 31,
            mealRecords: {},
            popupVisible: false,
            currentDate: '',
            currentMealType: '',
            searchKeyword: '',
            selectedFoods: []
        };
    },
    computed: {
        filteredFoodList() {
            if (!this.searchKeyword) return [];
            return foodList.filter((food) => food.names.toLowerCase().includes(this.searchKeyword.toLowerCase()));
        }
    },

    onLoad(options) {
        const user = uni.getStorageSync('user');
        this.currentDate = options.full;
        this.category = options.type;
        if (!user) {
            uni.showToast({
                title: '请先登录',
                icon: 'none'
            });
            setTimeout(() => {
                uni.redirectTo({
                    url: '/pages/login/login'
                });
            }, 1000);
        }
    },
    methods: {
        handleCancel() {
            uni.redirectTo({
                url: '/pages/index/index'
            });
        },

        // 获取餐饮热量
        getMealCalories(date, mealType) {
            if (this.mealRecords[date] && this.mealRecords[date][mealType]) {
                const foods = this.mealRecords[date][mealType];
                let totalCalories = 0;
                foods.forEach((item) => {
                    totalCalories += item.food.calories * item.amount;
                });
                return `${totalCalories.toFixed(0)}千卡`;
            }
            return null;
        },

        // 编辑餐饮
        editMeal(date, mealType) {
            this.currentDate = date;
            this.currentMealType = mealType;
            this.selectedFoods = [];

            // 加载已有的食物记录
            if (this.mealRecords[date] && this.mealRecords[date][mealType]) {
                this.selectedFoods = JSON.parse(JSON.stringify(this.mealRecords[date][mealType]));
            }

            this.popupVisible = true;
        },

        // 选择食物
        selectFood(food) {
            // 检查是否已经选择了该食物
            const existingIndex = this.selectedFoods.findIndex((item) => item.food.names === food.names);

            if (existingIndex >= 0) {
                // 如果已经选择了，增加数量
                this.selectedFoods[existingIndex].amount += 1;
            } else {
                // 否则添加到已选择列表
                this.selectedFoods.push({
                    food,
                    amount: 1
                });
            }
        },

        // 增加食物数量
        increaseAmount(index) {
            this.selectedFoods[index].amount += 1;
        },

        // 减少食物数量
        decreaseAmount(index) {
            if (this.selectedFoods[index].amount > 1) {
                this.selectedFoods[index].amount -= 1;
            }
        },

        // 移除食物
        removeFood(index) {
            this.selectedFoods.splice(index, 1);
        },

        // 计算总热量
        getTotalCalories() {
            let total = 0;
            this.selectedFoods.forEach((item) => {
                total += item.food.reliangNum * item.amount;
            });
            return total.toFixed(0);
        },

        // 保存餐饮记录
        saveMealRecord() {
            console.log(this.selectedFoods);
        },

        async addRecord() {
            if (this.selectedFoods.length == 0) {
                uni.showToast({
                    title: '请选择食物',
                    icon: 'none'
                });
                return;
            }
            const user = uni.getStorageSync('user');

            if (user) {
                await record.createRecord({
                    user_id: user._id,
                    category: this.category,
                    data: this.getTotalCalories(),
                    month_date: formatDate(new Date(this.currentDate), 'yyyy-MM'),
                    full_date: this.currentDate
                });
                uni.showToast({
                    title: '添加成功'
                });
                uni.$emit('refresh');
                this.selectedFoods = [];
            } else {
                uni.navigateTo({
                    url: '/pages/login/login'
                });
            }
        }
    }
};
</script>

<style lang="scss">
.container {
    min-height: 100vh;
    background-color: #f8f9fc;
    padding-bottom: 40rpx;
}

.status-bar {
    background-color: #fff;
    padding-top: env(safe-area-inset-top);
    padding-bottom: 20rpx;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    padding-right: 30rpx;
    position: relative;

    .nav-back {
        position: absolute;
        left: 30rpx;
        font-size: 40rpx;
        color: #333;
    }

    .title {
        flex: 1;
        text-align: center;
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
    }
}

.month-selector {
    margin: 30rpx;
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);

    .calendar-icon {
        color: #ff6b35;
        font-size: 40rpx;
        margin-right: 20rpx;
    }

    .date-range {
        flex: 1;
        font-size: 28rpx;
        color: #333;
    }

    .selector-arrows {
        display: flex;
        align-items: center;

        .tn-icon-left,
        .tn-icon-right {
            font-size: 32rpx;
            color: #666;
            padding: 10rpx;
        }
    }
}

.date-cards {
    height: calc(100vh - 240rpx);
    padding: 0 30rpx;
}

.date-card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    position: relative;

    .date-header {
        padding: 20rpx 30rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #f5f5f5;

        .date-day {
            display: flex;
            align-items: center;

            .date-icon {
                width: 60rpx;
                height: 60rpx;
                background-color: #5b67ca;
                color: #fff;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 28rpx;
                margin-right: 20rpx;
            }
        }

        .date-arrow {
            color: #999;
            font-size: 32rpx;
        }
    }

    .meal-records {
        display: flex;
        flex-wrap: wrap;
        padding: 20rpx;
    }

    .meal-item {
        width: 50%;
        padding: 20rpx;
        display: flex;
        align-items: center;

        .meal-icon {
            width: 60rpx;
            height: 60rpx;
            background-color: rgba(255, 107, 53, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ff6b35;
            font-size: 32rpx;
            margin-right: 20rpx;
        }

        .lunch-icon {
            background-color: rgba(255, 172, 0, 0.1);
            color: #ffac00;
        }

        .dinner-icon {
            background-color: rgba(251, 106, 103, 0.1);
            color: #fb6a67;
        }

        .snack-icon {
            background-color: rgba(149, 123, 254, 0.1);
            color: #957bfe;
        }

        .meal-name {
            font-size: 28rpx;
            color: #333;
            margin-right: 20rpx;
        }

        .meal-calories {
            font-size: 24rpx;
            color: #999;
        }
    }

    .delete-btn {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        width: 60rpx;
        height: 60rpx;
        background-color: #ff6b35;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #fff;
        font-size: 32rpx;
    }
}

.food-popup {
    padding: 30rpx;
    .popup-title {
        font-size: 32rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
        text-align: center;
    }

    .popup-date {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 30rpx;
        text-align: center;
    }

    .food-search {
        margin-bottom: 20rpx;
    }

    .food-list {
        height: 30vh;
        margin-bottom: 30rpx;
    }

    .food-item {
        padding: 20rpx 0;
        border-bottom: 1px solid #f5f5f5;
        display: flex;
        justify-content: space-between;

        .food-name {
            font-size: 28rpx;
            color: #333;
        }

        .food-calories {
            font-size: 24rpx;
            color: #999;
        }
    }

    .selected-foods {
        margin-top: 30rpx;
        padding-top: 30rpx;

        .selected-foods-list {
            background-color: #efefef;
            height: 30vh;
            padding: 20rpx;
        }
        .selected-title {
            font-size: 28rpx;
            font-weight: bold;
            margin-bottom: 20rpx;
        }

        .selected-food-item {
            display: flex;
            align-items: center;
            padding: 20rpx 0;
            border-bottom: 1px solid #f5f5f5;

            .selected-food-name {
                flex: 1;
                font-size: 28rpx;
                color: #333;
            }

            .selected-food-amount {
                display: flex;
                align-items: center;
                margin-right: 20rpx;

                .amount-btn {
                    width: 50rpx;
                    height: 50rpx;
                    background-color: #f5f5f5;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 28rpx;
                }

                .amount-value {
                    margin: 0 20rpx;
                    font-size: 28rpx;
                }
            }

            .selected-food-calories {
                font-size: 24rpx;
                color: #5b67ca;
                margin-right: 20rpx;
            }

            .remove-btn {
                color: #999;
                font-size: 32rpx;
            }
        }

        .total-calories {
            margin-top: 30rpx;
            font-size: 28rpx;
            font-weight: bold;
            color: #5b67ca;
            text-align: right;
        }
    }

    .popup-actions {
        margin-top: 30rpx;
        display: flex;
        justify-content: center;
        .save-btn {
            background-color: #5b67ca;
            color: #fff;
            text-align: center;
            padding: 20rpx;
            border-radius: 12rpx;
            font-size: 28rpx;
            width: 50%;
            margin: 0 20rpx;
            &.cancel{
                background-color: #fff;
                color: #5b67ca;
                border: 1px solid #5b67ca;
            }
        }
    }
}
</style>
